package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.astrob.activitys.DMapActivity;
import com.astrob.activitys.GPSProvider;
import com.astrob.model.LonLat;
import com.astrob.model.Msg;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.CoordChange;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.nhc.database.dbmodel.Route;
import com.nhc.database.dbmodel.WayPoint;
import com.nhc.database.dbmodel.WayTrail;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.database.manager.IECenter;
import com.nhc.database.manager.QiyaCenter;
import com.nhc.model.PoiCollectInfo;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.manager.TimeRefresher;
import zuo.biao.library.ui.AlertDialog;
import zuo.biao.library.ui.BottomMenuWindow;
import zuo.biao.library.ui.CutPictureActivity;
import zuo.biao.library.ui.EditTextInfoActivity;
import zuo.biao.library.ui.EditTextInfoWindow;
import zuo.biao.library.ui.SelectPictureActivity;
import zuo.biao.library.ui.ShowPictureActivity;
import zuo.biao.library.ui.TopMenuWindow;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.DataKeeper;
import zuo.biao.library.util.ImageLoaderUtil;
import zuo.biao.library.util.StringUtil;

public class MarkerPointActivity extends BaseActivity implements View.OnClickListener,
        AlertDialog.OnDialogButtonClickListener, TimeRefresher.OnTimeRefreshListener {

    private final String TAG = "MarkerPointActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    public static final String INTENT_MARKPOINT_DESIGN = "INTENT_MARKPOINT_DESIGN";
    public static final String INTENT_MARKPOINT_FORMLIST = "INTENT_MARKPOINT_FORMLIST";

    public static final String INTENT_MARKPOINT_NOMENU = "INTENT_MARKPOINT_NOMENU";

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, MarkerPointActivity.class);
    }

    public static Intent createIntent(Context context, boolean isDesign, boolean haveNavi) {
        return new Intent(context, MarkerPointActivity.class)
                .putExtra(INTENT_MARKPOINT_FORMLIST, haveNavi)
                .putExtra(INTENT_MARKPOINT_DESIGN, isDesign);
    }

    public static Intent createIntentNoMenu(Context context) {
        return new Intent(context, MarkerPointActivity.class)
                .putExtra(INTENT_MARKPOINT_NOMENU, true);
    }
    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    private WayPoint mWayPoint;

    boolean _isDesign;
    private WayPoint mWayPointDesign;

    boolean _haveNavi = false; //航点列表进入，可以navi

    boolean _noMenu = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.markerpoint_activity);

        intent = getIntent();
        _isDesign = intent.getBooleanExtra(INTENT_MARKPOINT_DESIGN, _isDesign);
        _haveNavi = intent.getBooleanExtra(INTENT_MARKPOINT_FORMLIST, _haveNavi);
        _noMenu = intent.getBooleanExtra(INTENT_MARKPOINT_NOMENU, _noMenu);

        mWayPoint = DBDataCenter.getInstance().makerEdit;
        if (mWayPoint == null) {
            setMarkerByLocaton();//SMF地图，回现在地后，长按地图取点
        }

        String name = mWayPoint.getName().trim();
        if (name.length() < 1) {
            name = DBDataCenter.getInstance().getNewWayPointDefaultName();
            mWayPoint.setName(name);
        }

        if (_noMenu) {
            findViewById(R.id.iv_rightmenu).setVisibility(View.GONE);
        }

        if (_isDesign) {
            mWayPointDesign = new WayPoint(mWayPoint, 0L);
            mWayPointDesign.setType(0);
            mWayPointDesign.setPicurl("");
            mWayPointDesign.setName(mWayPointDesign.getName() + getString(R.string.newdesign));
        }

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }

    private void setMarkerByLocaton() {
        LonLat ll = SysUtils.getInstance().getLL();
        WayPoint wp = DBDataCenter.getInstance().createNewWayPoint(ll);
        wp.setAltitude(GPSProvider.getInstance().getAltitude());
        if (QiyaCenter.getInstance()._thisQiyaInfo != null) {
            double qiyaH = QiyaCenter.getInstance()._thisQiyaInfo.getAltitude();
            double H = wp.getAltitude();
            if (Math.abs((int) (qiyaH - H)) < 100 || H == 0) {
                //气压高度误差太大；可能气压高度是不准确的则不用
                wp.setAltitude(qiyaH);
            }
        }
        DBDataCenter.getInstance().makerEdit = wp;
        mWayPoint = DBDataCenter.getInstance().makerEdit;
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private ScrollView svDemoMain;
    private TextView tvNpname;
    private TextView tv_note;
    private TextView tvLat;
    private TextView tv_npaltitude;
    private TextView tvNptime;
    private ImageView ivIcon;
    private ImageView ivImage;
    private TextView bt_pinjun;
    private TextView bt_save;
    private TextView bt_navi;

    private TextView tv_distance;
    private TextView tv_dir;
    private TextView tv_fuyangjiao;

    private TextView tv_warningrange;

    @Override
    public void initView() {//必须调用
        tvNpname = (TextView) findViewById(R.id.tv_npname);
        tv_note = (TextView) findViewById(R.id.tv_note);
        tvLat = (TextView) findViewById(R.id.tv_lat);
        tv_npaltitude = (TextView) findViewById(R.id.tv_npaltitude);
        tvNptime = (TextView) findViewById(R.id.tv_nptime);
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        ivImage = (ImageView) findViewById(R.id.iv_image);
        svDemoMain = (ScrollView) findViewById(R.id.svDemoMain);
        bt_pinjun = (TextView) findViewById(R.id.bt_pinjun);

        bt_save = (TextView) findViewById(R.id.bt_save);
        bt_navi = (TextView) findViewById(R.id.bt_navi);

        tv_distance = (TextView) findViewById(R.id.tv_distance);
        tv_dir = (TextView) findViewById(R.id.tv_dir);
        tv_fuyangjiao = (TextView) findViewById(R.id.tv_fuyangjiao);

        tv_warningrange = (TextView) findViewById(R.id.tv_warningrange);

        if (_isDesign) {
            findViewById(R.id.iv_rightmenu).setVisibility(View.GONE);
            findViewById(R.id.npdetail_3).setVisibility(View.GONE);
            findViewById(R.id.ll_makerdesign_0).setVisibility(View.VISIBLE);
            findViewById(R.id.ll_makerdesign_1).setVisibility(View.VISIBLE);
            findViewById(R.id.ll_makerdesign_2).setVisibility(View.VISIBLE);
            findViewById(R.id.bt_map).setVisibility(View.VISIBLE);
            bt_pinjun.setVisibility(View.GONE);

            String strUnit = " m";
            switch (SysUtils.getInstance().dis_mode) {
                default:
                    break;
                case 4:
                case 1:
                    strUnit = " ft";
                    break;
                case 2:
                    strUnit = " yd";
                    break;
            }
            tv_distance.setText(0 + strUnit);
        }

        if (_haveNavi) {
            findViewById(R.id.bt_map).setVisibility(View.VISIBLE);
            bt_pinjun.setVisibility(View.GONE);
            bt_save.setVisibility(View.GONE);
            bt_navi.setVisibility(View.VISIBLE);
        }
//            bt_save.requestFocus();

    }


    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


    @Override
    public void initData() {//必须调用
        WayPoint wt = mWayPoint;
        if (_isDesign) {
            wt = mWayPointDesign;
        }

        if (wt.getType() == 0) {
            findViewById(R.id.ll_warning).setVisibility(View.GONE);
        } else {
            findViewById(R.id.ll_warning).setVisibility(View.VISIBLE);
        }

        String RR[] = SysUtils.getInstance().getAltitudeStr(wt.getRange());
        tv_warningrange.setText(RR[0] + RR[1]);

        tvNpname.setText(wt.getName());
        tv_note.setText(wt.getNote());

        int coord_mode = SysUtils.getInstance().coord_mode;
        int coord_format = SysUtils.getInstance().coord_format;
        if (mWayPoint.coord_mode == coord_mode
                && mWayPoint.coord_format == coord_format
                && mWayPoint.strLL != null
                && mWayPoint.strLL.length() > 0) {
            tvLat.setText(mWayPoint.strLL);//getLLStr--已经转换
        } else {
            tvLat.setText(SysUtils.getInstance().getLLStr(mWayPoint.getLL()));//getLLStr--已经转换
        }


        String alt[] = SysUtils.getInstance().getAltitudeStr(wt.getAltitude());
        tv_npaltitude.setText(alt[0] + alt[1]);
        tvNptime.setText(SysUtils.getInstance().getTimeStr(wt.getDatetime()));
        ivIcon.setImageResource(wt.getTypeIcon());

        if (StringUtil.isFilePath(wt.getPicurl()) != false) {
            picturePath = wt.getPicurl();
            setPicture(picturePath);
        }

        double distance = Start.getInstance().MapKit().getDistance(wt.getLL(), SysUtils.getInstance().getLL());
        if (distance > 100) {
            bt_pinjun.setEnabled(false);
        }

        if (wt.getType() == 1) {
            tvNpname.setTextColor(context.getResources().getColor(R.color.orangered));
        } else {
            tvNpname.setTextColor(context.getResources().getColor(R.color.nhc_maintab_txt_normal));
        }
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void initEvent() {//必须调用
        findViewById(R.id.npdetail_0).setOnClickListener(this);
        findViewById(R.id.npdetail_1).setOnClickListener(this);
        findViewById(R.id.npdetail_2).setOnClickListener(this);
        findViewById(R.id.npdetail_3).setOnClickListener(this);
        findViewById(R.id.npdetail_5).setOnClickListener(this);
        findViewById(R.id.npdetail_6).setOnClickListener(this);
        findViewById(R.id.layout_image).setOnClickListener(this);

        findViewById(R.id.ll_makerdesign_0).setOnClickListener(this);
        findViewById(R.id.ll_makerdesign_1).setOnClickListener(this);
        findViewById(R.id.ll_makerdesign_2).setOnClickListener(this);

        findViewById(R.id.ll_warning).setOnClickListener(this);

        findViewById(R.id.bt_pinjun).setOnClickListener(this);
        findViewById(R.id.bt_map).setOnClickListener(this);
        findViewById(R.id.bt_save).setOnClickListener(this);
        findViewById(R.id.bt_navi).setOnClickListener(this);

    }
    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            default:
                break;
            case 21://left
            case 22://right
            case 19://up
            case 20://down
            case 23://ok
                setFoucseCtrl();
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    boolean _isFirst = true;

    private void setFoucseCtrl() {
        if (!_isFirst) {
            return;
        }

        _isFirst = false;

        for (int i = 0; i < CTRL_IDS.length; i++) {
            findViewById(CTRL_IDS[i]).setFocusable(true);
        }
        if (_haveNavi) {
            findViewById(R.id.bt_navi).requestFocus();
        } else {
            findViewById(R.id.bt_save).requestFocus();
        }
    }

    private int[] CTRL_IDS = {
            R.id.npdetail_0, R.id.npdetail_1, R.id.npdetail_2,
            R.id.npdetail_3, R.id.npdetail_4, R.id.npdetail_5,
            R.id.npdetail_6, R.id.layout_image,
            R.id.ll_makerdesign_0, R.id.ll_makerdesign_1, R.id.ll_makerdesign_2,
            R.id.bt_pinjun, R.id.bt_save, R.id.bt_map, R.id.bt_navi};


    void doSelect(int id) {

        switch (id) {
            case R.id.npdetail_0:
                toActivity(SelectIconActivity.createIntent(context, 0), SELECTICON);
                break;
            case R.id.npdetail_1:
                editName(true);
                break;
            case R.id.npdetail_2:
                editLonLat();
                break;
            case R.id.npdetail_3:
                editHeight();
                break;
            case R.id.npdetail_5:
                selectPicture();
                break;
            case R.id.npdetail_6:
                editNote(true);
                break;
            case R.id.layout_image:
                showBigPic();
                break;
            case R.id.ll_makerdesign_0:
                editDistance();
                break;
            case R.id.ll_makerdesign_1:
                editDir();
                break;
            case R.id.ll_makerdesign_2:
                editFuyangjiao();
                break;
            case R.id.ll_warning:
                setAsWarningPt();
                break;
            case R.id.bt_pinjun:
                onPinJun();
                break;
            case R.id.bt_save:
                onSave();
                break;
            case R.id.bt_map:
                onMap();
                break;
            case R.id.bt_navi:
                onNavi();
                break;
            default:
                break;
        }
    }


    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    @Override
    public void finish() {
        if (_haveNavi) {
            //如果没有保存按键，返回就保存
            DBDataCenter.getInstance().saveWayPoint(mWayPoint);
        }
        super.finish();
    }

    private void onShare() {
        // 分享位置
//        CommonUtil.shareInfo(context, tvLat.getText().toString());
        showProgressDialog(R.string.loading);
        runThread(TAG + "daochuData", new Runnable() {
            @Override
            public void run() {
                ArrayList<WayPoint> naviPtList = new ArrayList<WayPoint>();
                naviPtList.add(mWayPoint);

                SimpleDateFormat formatter = new SimpleDateFormat(
                        "yyyyMMdd_HHmmss");
                Date curDate = new Date(System.currentTimeMillis());
                String suffix = "naviPtX_" + formatter.format(curDate);

                File file1 = new File(IECenter.EXDIR_GPX);
                if (!file1.exists()) {
                    file1.mkdirs();
                }

                final String savePath = IECenter.EXDIR_GPX + suffix + ".gpx";
                File gpxFile = new File(savePath);
                if (!gpxFile.exists()) {
                    IECenter.getInstance().export2GPX(suffix, naviPtList, null, null);
                }
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        doShare(savePath);
                    }
                });
            }
        });
    }

    void doShare(String savePath) {
        ArrayList<Uri> files = new ArrayList<Uri>();
        files.add(Uri.fromFile(new File(savePath)));
        Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);//发送多个文件
        intent.setType("*/*");//多个文件格式
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);//Intent.EXTRA_STREAM同于传输文件流
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        TimeRefresher.getInstance().removeTimeRefreshListener(TAG);
    }

    @Override
    public void onForwardClick(View v) {
        //top栏右边按钮响应

        toActivity(TopMenuWindow.createIntent(context, getResources().getStringArray(R.array.top_menu_markpt)), REQUEST_TO_TOP_MENU, false);
    }

    @Override
    public void onClick(View v) {
        int ctrlID = v.getId();
        doSelect(ctrlID);
    }

    double _distance = 0;
    int _dir = 0;
    int _fuyangjiao = 0;

    private void editDistance() {
        String strUnit = "m";
        double distance = _distance;
        switch (SysUtils.getInstance().dis_mode) {
            default:
                break;
            case 4:
            case 1:
                distance = distance * 3.2808399;
                strUnit = "ft";
                break;
            case 2:
                distance = distance * 1.0936133;
                strUnit = "yd";
                break;
        }

        intent = EditNumberActivity.createIntentD(context
                , getString(R.string.xgjl), _distance, strUnit);
        toActivity(intent, REQUEST_TO_DISTANCE);
    }

    private void editDir() {
        toActivity(BottomMenuWindow.createIntent(context, getResources().getStringArray(R.array.edit_dirs))
                .putExtra(BottomMenuWindow.INTENT_TITLE, getString(R.string.xgfx)), REQUEST_TO_BOTTOM_MENU_1, false);
    }

    private void editFuyangjiao() {
        intent = EditNumberActivity.createIntent(context
                , getString(R.string.xgfyj), _fuyangjiao, getString(R.string.du));
        toActivity(intent, REQUEST_TO_FUYANGJIAO);
    }

    void showBigPic() {
        if (picturePath == null)
            return;

        if (StringUtil.isFilePath(picturePath) != false) {
            toActivity(ShowPictureActivity.createIntent(context, picturePath));
        }
    }

    private String picturePath;

    private void selectPicture() {
        String dirPath = "";
        if (SysUtils.getInstance().is240x320) {
            dirPath = Environment.getExternalStorageDirectory() + "/DCIM";
        }
        toActivity(SelectPictureActivity.createIntent2(context, dirPath), REQUEST_TO_SELECT_PICTURE, false);
    }

    /**
     * 裁剪图片
     *
     * @param path
     */
    private void cutPicture(String path) {
        if (StringUtil.isFilePath(path) == false) {
            showShortToast(getString(R.string.tnopic));
            return;
        }
        this.picturePath = path;

        toActivity(CutPictureActivity.createIntent(context, path
                , DataKeeper.imagePath, "photo" + System.currentTimeMillis(), 200)
                , REQUEST_TO_CUT_PICTURE);
    }

    /**
     * 显示图片
     *
     * @param path
     */
    private void setPicture(String path) {
        if (StringUtil.isFilePath(path) == false) {
            showShortToast(getString(R.string.tnopic));
            return;
        }
//        this.picturePath = path;
        if (_isDesign) {
            mWayPointDesign.setPicurl(path);
        } else {
            mWayPoint.setPicurl(path);
        }

        svDemoMain.smoothScrollTo(0, 0);
        ImageLoaderUtil.loadImage(ivImage, path);
    }

    private void editName(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NICK
                    , getString(R.string.navipiname), StringUtil.getTrimedString(tvNpname), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NICK
                    , getString(R.string.navipiname), StringUtil.getTrimedString(tvNpname));
        }

        toActivity(intent, REQUEST_TO_EDIT_TEXT_INFO, !toWindow);
    }

    private void editNote(boolean toWindow) {
        if (toWindow) {
            intent = EditTextInfoWindow.createIntent(context, EditTextInfoWindow.TYPE_NOTE
                    , getString(R.string.naviptnote_t), StringUtil.getTrimedString(tv_note), getPackageName());
        } else {
            intent = EditTextInfoActivity.createIntent(context, EditTextInfoActivity.TYPE_NOTE
                    , getString(R.string.naviptnote_t), StringUtil.getTrimedString(tv_note));
        }

        toActivity(intent, REQUEST_TO_EDIT_NOTE, !toWindow);
    }

    private void editHeight() {
        String strUnit = "m";
        double alt = mWayPoint.getAltitude();
        switch (SysUtils.getInstance().dis_mode) {
            default:
                break;
            case 4:
            case 1:
                alt = alt * 3.2808399;
                strUnit = "ft";
                break;
            case 2:
                alt = alt * 1.0936133;
                strUnit = "yd";
                break;
        }
        intent = EditNumberActivity.createIntentD(context
                , getString(R.string.xghdgd), (float) alt, strUnit);
        toActivity(intent, REQUEST_TO_EDIT_HEIGHT_INFO);
    }

    private void editLonLat() {
        int coord_mode = SysUtils.getInstance().coord_mode;
        int coord_format = SysUtils.getInstance().coord_format;

        if (mWayPoint.coord_mode == coord_mode
                && mWayPoint.coord_format == coord_format
                && mWayPoint.strLL != null
                && mWayPoint.strLL.length() > 0) {
            intent = EditLonLatActivity.createIntentStrLL(context
                    , mWayPoint.strLL);
        } else {
            intent = EditLonLatActivity.createIntent(context
                    , mWayPoint.getLL());
        }

        toActivity(intent, REQUEST_TO_EDIT_LONLAT_INFO);
    }

    private ArrayList<LonLat> pinjunList = new ArrayList<LonLat>();

    @Override
    public void onTimerStart() {

    }

    private int count = 0;
    private boolean isToStop = true;

    @Override
    public void onTimerRefresh() {
        if (isToStop == false) {
            count++;
            doPinJun();
        }
    }

    @Override
    public void onTimerStop() {

    }

    void onPinJun() {
        //开启平均timer
        if (isToStop) {
            isToStop = false;
            TimeRefresher.getInstance().addTimeRefreshListener(TAG
                    , 2000, this);
        }

    }

    private void doPinJun() {
        LonLat llcar = SysUtils.getInstance().getLL();
        double distance = Start.getInstance().MapKit().getDistance(llcar, mWayPoint.getLL());
        if (distance > 100) {
            showShortToast(getString(R.string.taddpterr));
        } else {
            pinjunList.add(llcar);
            bt_pinjun.setText(getString(R.string.pingjun_t0) + pinjunList.size() + ")");
            bt_pinjun.setTextColor(Color.BLUE);
            pinjunLL = getPinjunLL();
            tvLat.setTextColor(Color.BLUE);
            tvLat.setText(SysUtils.getInstance().getLLStr(pinjunLL));
        }
    }

    LonLat pinjunLL;

    public LonLat getPinjunLL() {
        double lon = mWayPoint.getLL().GetLon();
        double lat = mWayPoint.getLL().GetLat();

        int size = pinjunList.size();
        if (size > 0) {
            for (LonLat pos : pinjunList) {
                lon += pos.GetLon();
                lat += pos.GetLat();
            }
            lon = lon / (size + 1);
            lat = lat / (size + 1);
        }

        return new LonLat(lon, lat);
    }

    void onSave() {
        if (_isDesign) {
            if (_distance > 0) {
                LonLat ll = Utils.getLLByLLAngle(mWayPointDesign.getLL(), _dir, _distance * Math.cos(_fuyangjiao * Math.PI / 180));
                String a = Start.getInstance().MapKit().getDirection(mWayPointDesign.getLL(), ll);
                mWayPointDesign.setLL(ll);
                double alt = mWayPoint.getAltitude() + _distance * Math.sin(_fuyangjiao * Math.PI / 180);
                mWayPointDesign.setAltitude(alt);
            }

            if (DBDataCenter.getInstance().saveWayPoint(mWayPointDesign) > 0) {

                Utils.writeLatLonIntoJpeg(mWayPoint.getPicurl(), mWayPoint.getLL().GetLat(), mWayPoint.getLL().GetLon());
                showShortToast(getString(R.string.daddptok));
                finish();
            }
        } else {
            if (pinjunLL != null) {
                mWayPoint.setLL(pinjunLL);
            }
            if (DBDataCenter.getInstance().saveWayPoint(mWayPoint) > 0) {
                LonLat llA = mWayPoint.getLL();
                Utils.writeLatLonIntoJpeg(mWayPoint.getPicurl(), mWayPoint.getLL().GetLat(), mWayPoint.getLL().GetLon());

                LonLat ll = Utils.getExifLonLat(mWayPoint.getPicurl());
                showShortToast(getString(R.string.saveok));
                finish();
            }
        }
    }

    void onMap() {
        WayPoint wt = mWayPoint;
        if (_isDesign) {
            wt = mWayPointDesign;
            toActivity(DMapActivity.createIntent(context, wt.getName()
                    , wt.getLL()), REQUEST_TO_ONMAP);
        } else {
            DBDataCenter.getInstance().makerEdit = mWayPoint;
            toActivity(DMapActivity.createIntentFromEdit(context), REQUEST_TO_ONMAP);
        }
    }

    void onNavi() {
        if (DBDataCenter.getInstance().routeNavi != null) {
            new AlertDialog(context, "", getString(R.string.qstopdest) + mWayPoint.getName() + "？", true, 11, this).show();
        } else if (DBDataCenter.getInstance().wayTrailNavi != null) {
            new AlertDialog(context, "", getString(R.string.qstopdest_line) + mWayPoint.getName() + "？", true, 11, this).show();
        } else if (Start.getInstance().isHavePath()) {
            new AlertDialog(context, "", getString(R.string.qdzzdqdhrhksxddh), true, 11, this).show();
        } else {
            DBDataCenter.getInstance().makerNavi = mWayPoint;
            setResult(Msg.NAVI_TO_DEST);
            finish();
        }
    }

    public void onReturnClick(View v) {
        if (_haveNavi) {
            WayPoint wt = mWayPoint;
            if (_isDesign) {
                wt = mWayPointDesign;
            }
            DBDataCenter.getInstance().saveWayPoint(wt);
        }

        finish();
    }

    private final int REQUEST_TO_SELECT_PICTURE = 20;
    private final int REQUEST_TO_CUT_PICTURE = 21;
    private final int REQUEST_TO_EDIT_TEXT_INFO = 23;
    private final int REQUEST_TO_EDIT_HEIGHT_INFO = 24;
    private final int REQUEST_TO_EDIT_LONLAT_INFO = 25;
    private final int REQUEST_TO_TOP_MENU = 30;
    private final int REQUEST_TO_EDIT_NOTE = 31;

    private final int SELECTICON = 33;
    private final int REQUEST_TO_EDIT_RANGE = 34;
    private final int REQUEST_TO_ADDLINE = 35;

    private final int REQUEST_TO_DISTANCE = 36;
    private final int REQUEST_TO_DIR = 37;
    private final int REQUEST_TO_FUYANGJIAO = 38;
    private final int REQUEST_TO_ONMAP = 40;
    private final int REQUEST_TO_BOTTOM_MENU_1 = 41;
    private final int REQUEST_TO_COMPASS = 42;

    private final int REQUEST_TO_SELECT_ALBUM = 43;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Msg.NAVI_TO_DEST) {
            setResult(resultCode);
            finish();
            return;
        }

        if (requestCode == SELECTICON) {
            setMarkerIcon(resultCode);
            return;
        }

        if (requestCode == REQUEST_TO_ONMAP) {
            //移动航点
            tvLat.setText(SysUtils.getInstance().getLLStr(mWayPoint.getLL()));
            return;
        }

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_TO_COMPASS:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    _dir = data.getIntExtra(CompassActivity.RESULT_VALUE, _dir);
                    tv_dir.setText(_dir + getString(R.string.ddu));
                }
                break;
            case REQUEST_TO_BOTTOM_MENU_1:
                if (data != null) {
                    int selectedPosition = data.getIntExtra(BottomMenuWindow.RESULT_ITEM_ID, -1);
                    if (selectedPosition == 0) {
                        toActivity(CompassActivity.createIntent(this), REQUEST_TO_COMPASS);
                    } else {
                        intent = EditNumberActivity.createIntent(context
                                , getString(R.string.xgfx), _dir, getString(R.string.du));
                        toActivity(intent, REQUEST_TO_DIR);
                    }
                }
                break;
            case REQUEST_TO_EDIT_TEXT_INFO:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tvNpname.setText(name);
                    if (_isDesign) {
                        mWayPointDesign.setName(name);
                    } else {
                        mWayPoint.setName(name);
                    }
                }
                break;
            case REQUEST_TO_EDIT_NOTE:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String name = StringUtil.getTrimedString(
                            data.getStringExtra(EditTextInfoWindow.RESULT_VALUE));
                    tv_note.setText(name);
                    if (_isDesign) {
                        mWayPointDesign.setNote(name);
                    } else {
                        mWayPoint.setNote(name);
                    }
                }
                break;
            case REQUEST_TO_EDIT_HEIGHT_INFO:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String editedValue = data.getStringExtra(EditTextInfoWindow.RESULT_VALUE);
                    double alt = Double.valueOf(editedValue);
                    switch (SysUtils.getInstance().dis_mode) {
                        default:
                            break;
                        case 1:
                        case 4:
                            //ft => m
                            alt = alt / 3.2808399;
                            break;
                        case 2: {
                            //yd => m
                            alt = alt / 1.0936133;
                        }
                        break;
                    }
                    mWayPoint.setAltitude(alt);
                    String ALT[] = SysUtils.getInstance().getAltitudeStr(mWayPoint.getAltitude());
                    tv_npaltitude.setText(ALT[0] + ALT[1]);
                }
                break;
            case REQUEST_TO_EDIT_LONLAT_INFO:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    LonLat llA = null;
                    int coord_mode = SysUtils.getInstance().coord_mode;
                    int coord_format = SysUtils.getInstance().coord_format;
                    String strLL = "";
                    if (coord_format > 2) {
                        strLL = data.getStringExtra(EditTextInfoWindow.RESULT_VALUE);
                        tvLat.setText(strLL);
                        //大地坐标->GPS坐标->火星坐标---保存
                        llA = CoordChange.getInstance().change2LL(strLL, coord_mode, coord_format);

//                        LonLat B = mWayPoint.getLL();
//
//                        String strLLA = SysUtils.getInstance().getLLStr(llA);
//                        int a = 0;
//                        a++;
                    } else {
                        llA = (LonLat) data.getSerializableExtra(EditTextInfoWindow.RESULT_VALUE);
                        llA = CoordChange.getInstance().getLL(llA.GetLon(), llA.GetLat(), 0, "", coord_mode, coord_format);
                        tvLat.setText(SysUtils.getInstance().getLLStr(llA));
                    }

                    if (llA != null) {
                        if (_isDesign) {
                            mWayPointDesign.setLL(llA);
                            mWayPointDesign.strLL = strLL;
                            mWayPointDesign.coord_mode = coord_mode;
                            mWayPointDesign.coord_format = coord_format;
                        } else {
                            mWayPoint.setLL(llA);
                            mWayPoint.strLL = strLL;
                            mWayPoint.coord_mode = coord_mode;
                            mWayPoint.coord_format = coord_format;
                        }
                    }

                    String ALT[] = SysUtils.getInstance().getAltitudeStr(mWayPoint.getAltitude());
                    tv_npaltitude.setText(ALT[0] + ALT[1]);
                }
                break;
            case REQUEST_TO_SELECT_PICTURE:
                if (data != null) {
//                    cutPicture(data.getStringExtra(SelectPictureActivity.RESULT_PICTURE_PATH));
                    String strPath = data.getStringExtra(SelectPictureActivity.RESULT_PICTURE_PATH);
                    if (strPath.length() > 1) {
                        setPicture(strPath);
                    } else {
                        //选相册
                        toActivity(PhotoAlbumActivity.createIntentSelect(getBaseContext()), REQUEST_TO_SELECT_ALBUM);
                    }
                }
                break;
            case REQUEST_TO_SELECT_ALBUM:
                if (data != null) {
                    String strPath = data.getStringExtra(PhotoAlbumActivity.RESULT_PICTURE_PATH);
                    setPicture(strPath);
                }
                break;
            case REQUEST_TO_CUT_PICTURE:
                if (data != null) {
                    setPicture(data.getStringExtra(CutPictureActivity.RESULT_PICTURE_PATH));
                }
                break;
            case REQUEST_TO_TOP_MENU:
                if (data != null) {
                    switch (data.getIntExtra(TopMenuWindow.RESULT_POSITION, -1)) {
                        case 0:
                            searchNear();
                            break;
                        case 1:
                            addToNaviLine();
                            break;
                        case 2:
                            designNewpt();
                            break;
                        case 3:
                            setAsWarningPt();
                            break;
                        case 4:
                            onShare();
                            break;
                        default:
                            break;
                    }
                }
                break;
            case REQUEST_TO_EDIT_RANGE:
                if (data != null) {
                    String editedValue = data.getStringExtra(EditNumberActivity.RESULT_VALUE);
                    double range = Double.valueOf(editedValue);
                    switch (SysUtils.getInstance().dis_mode) {
                        default:
                            break;
                        case 1:
                        case 4:
                            //ft => m
                            range = range / 3.2808399;
                            break;
                        case 2: {
                            //yd => m
                            range = range / 1.0936133;
                        }
                        break;
                    }
                    addWarningPt(range);
                }
                break;
            case REQUEST_TO_ADDLINE:
                if (data != null) {
                    String editedValue = data.getStringExtra(NaviLineActivity.RESULT_VALUE);
                    long id = Long.valueOf(editedValue);
                    savePtToNaviline(id);
                }
                break;
            case REQUEST_TO_DISTANCE:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String editedValue = data.getStringExtra(EditTextInfoWindow.RESULT_VALUE);
                    _distance = Double.valueOf(editedValue);
                    switch (SysUtils.getInstance().dis_mode) {
                        default:
                            break;
                        case 1:
                        case 4:
                            //ft => m
                            _distance = _distance / 3.2808399;
                            break;
                        case 2: {
                            //yd => m
                            _distance = _distance / 1.0936133;
                        }
                        break;
                    }
                    String AA[] = SysUtils.getInstance().getAltitudeStr(_distance);
                    tv_distance.setText(AA[0] + AA[1]);
                }
                break;
            case REQUEST_TO_DIR:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String editedValue = data.getStringExtra(EditTextInfoWindow.RESULT_VALUE);
                    _dir = Integer.valueOf(editedValue);
                    tv_dir.setText(_dir + getString(R.string.ddu));
                }
                break;
            case REQUEST_TO_FUYANGJIAO:
                if (data != null) {
                    svDemoMain.smoothScrollTo(0, 0);
                    String editedValue = data.getStringExtra(EditTextInfoWindow.RESULT_VALUE);
                    _fuyangjiao = Integer.valueOf(editedValue);
                    tv_fuyangjiao.setText(_fuyangjiao + getString(R.string.ddu));
                }
                break;
        }
    }

    private void designNewpt() {
        toActivity(MarkerPointActivity.createIntent(this, true, false), 0);
    }

    private void savePtToNaviline(long routeId) {
        if (routeId == 0L) {
            return;
        }

        Route route = DBDataCenter.getInstance().getRouteById(routeId);
        if (route == null) {
            return;
        }

        Long wpId = DBDataCenter.getInstance().saveWayPoint(new WayPoint(mWayPoint, routeId));
        if (wpId == 0L) {
            return;
        }
        String strWps = route.getWaypoint();
        if (strWps.length() < 1) {
            strWps = wpId + "";
        } else {
            strWps += "-" + wpId;
        }
        route.setWaypoint(strWps);
        DBDataCenter.getInstance().saveRoute(route);
        showShortToast(getString(R.string.addpttoline0) + route.getName() + getString(R.string.addpttoline1));
    }

    private void addToNaviLine() {
        Intent intent = NaviLineActivity.createIntent(this, true);
        startActivityForResult(intent, REQUEST_TO_ADDLINE);
    }

    private void searchNear() {
        toActivity(SearchTypeActivity.createIntent(this, false), 5);
    }

    private void setAsWarningPt() {
        WayPoint wt = mWayPoint;
        if (_isDesign) {
            wt = mWayPointDesign;
        }
        double range = wt.getRange();
        if (range < 1) {
            range = 50;
        }
        String strUnit = "m";
        switch (SysUtils.getInstance().dis_mode) {
            default:
                break;
            case 4:
            case 1:
                range = range * 3.2808399;
                strUnit = "ft";
                break;
            case 2:
                range = range * 1.0936133;
                strUnit = "yd";
                break;
        }
        Intent intent = EditNumberActivity.createIntentD(this, getString(R.string.szjgfw), range, strUnit);
        startActivityForResult(intent, REQUEST_TO_EDIT_RANGE);

    }

    private void addWarningPt(double range) {
        WayPoint wt = mWayPoint;
        if (_isDesign) {
            wt = mWayPointDesign;
        }

        wt.setType(1);
        wt.setRange(range);
        initData();
//        showShortToast("已设置为警告点！");
    }

    private void setMarkerIcon(int icon_num) {
        if (icon_num < 0 || icon_num >= WayPoint.TYPE_IDS.length) {
            return;
        }
        if (_isDesign) {
            mWayPointDesign.setIcon_num(icon_num);
            ivIcon.setImageResource(mWayPointDesign.getTypeIcon());
        } else {
            mWayPoint.setIcon_num(icon_num);
            ivIcon.setImageResource(mWayPoint.getTypeIcon());
        }

    }

    @Override
    public void onDialogButtonClick(int requestCode, boolean isPositive) {
        if (isPositive == false) {
            return;
        }

        if (requestCode == 11) {
            DBDataCenter.getInstance().routeNavi = null;
            DBDataCenter.getInstance().wayTrailNavi = null;
            DBDataCenter.getInstance().makerNavi = mWayPoint;
            setResult(Msg.NAVI_TO_DEST);
            finish();
        }

    }
    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


}
